//
//  MineOrderHeaderView.m
//  B2C
//
//  Created by 李小龙 on 2017/7/31.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "MineOrderHeaderView.h"
#import "NumberTitleButton.h"

@interface MineOrderHeaderView()
{
    NSInteger _oldSelectedTag;
}
@end

@implementation MineOrderHeaderView

- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSArray *)titleArray selectIndex:(NSInteger)selectIndex {
    self = [super initWithFrame:frame];
    if (self) {
        _titleArray = titleArray;
        _selectIndex = selectIndex;
        _oldSelectedTag = selectIndex;
        
        [self setBackgroundColor:[UIColor whiteColor]];
        [self setBorderWithTop:YES left:NO bottom:YES right:NO borderColor:[UIColor borderColor] borderWidth:0.5f];
        
        [self createrButton];
    }
    return self;
}
- (void)createrButton {
    CGFloat BWidth = ScreenWidth/self.titleArray.count;
    CGFloat BHeight = self.height;
    for (int i = 0; i < self.titleArray.count; i++) {
        NSMutableDictionary *dic = self.titleArray[i];
        NumberTitleButton *button = [[NumberTitleButton alloc] initWithFrame:CGRectMake(i*BWidth, 0, BWidth, BHeight) number:nil title:dic[@"title"] showRightLine:YES messageNum:dic[@"number"] showRedPoint:YES];
        [button setTag:i+200];
        if (i == self.titleArray.count-1) {
            [button hiddenRightLine];
        }
        if (i == self.selectIndex) {
            [button setSelected:YES];
        }
        [self addSubview:button];
        button.block = ^(NSInteger tag) {
            if (_oldSelectedTag != tag) {
                _oldSelectedTag = tag;
                for (NumberTitleButton *temp in self.subviews) {
                    if ([temp isKindOfClass:[NumberTitleButton class]] && temp.selected && temp != button) {
                        [temp setSelected:NO];
                        break;
                    }
                }
                if (self.block) {
                    self.block(tag);
                }
            }
        };
    }
}
- (void)updateWith:(NSArray *)titleArray {
    self.titleArray = titleArray;
    for (NSInteger i = 0; i < self.titleArray.count; i++) {
        NSMutableDictionary *dic = self.titleArray[i];
        NumberTitleButton *button = (NumberTitleButton *)[self viewWithTag:i+200];
        [button.textLabel setText:dic[@"title"]];
        [button setRedPointText:dic[@"number"]];
        if ([dic[@"number"] isEqualToString:@"0"]) {
            [button hiddenRedPoint];
        } else {
            [button showRedPoint];
        }
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
